/*
 * @Author: your name
 * @Date: 2021-04-27 09:10:39
 * @LastEditTime: 2021-04-27 15:07:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \webpackstudy\src\modules\Calculator.js
 */

import { trimSpace, digitalization } from '../until/tools';
import Complute from '../lib/Complute';

export default class Calculator extends Complute{

    // 构造器
    constructor(el){
        super();
        this.name = "Calculator";
        
        this.oResult = el.getElementsByClassName('result')[0];
        this.oBtnGroup = el.getElementsByClassName('btn-group')[0];
        this.oInputs = el.getElementsByClassName('num-input');
    };

    // 入口函数
    init(){
        this.bindEvent();
    };

    // 绑定事件处理函数
    bindEvent(){
        this.oBtnGroup.addEventListener('click',this.btnClick.bind(this),false);
    };

    // 点击事件
    btnClick(ev){
        const e = ev || window.event,
              tar = e.target || e.srcElement,
              tagName = tar.tagName.toLowerCase();

        if(tagName === "button"){
            const method = tar.getAttribute("data-method"),
                fVal = digitalization(trimSpace(this.oInputs[0].value)),
                sVal = digitalization(trimSpace(this.oInputs[1].value));

            this.setResult(method,fVal,sVal);
        }
    };

    // 渲染方法
    setResult(method,fVal,sVal){
        this.oResult.innerText = this[method](fVal,sVal);
    };

};